<template>
  <div class="medicine-management">
    <!-- 添加按钮容器，用于居中 -->
    <div class="button-container">
      <el-button 
        type="primary" 
        size="small" 
        style="margin-bottom: 15px;"
        @click="openAddDialog()"
      >
        新增药品
      </el-button>
    </div>

    <!-- 药品表格容器，限制最大宽度并居中 -->
    <div class="table-container">
      <el-table 
        :data="medicalRecords" 
        style="width: 100%;"
        class="custom-table"
      >
        <el-table-column prop="medicine_id" label="药品ID" width="120" />
        <el-table-column prop="medicine_name" label="药品名称" width="180" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            {{ row.type === 0 ? '西药' : '中成药' }}
          </template>
        </el-table-column>
        <el-table-column prop="specifications" label="规格" width="200" />
        <el-table-column prop="stock" label="库存" width="120">
          <template #default="{ row }">
            {{ row.stock }} {{ row.unit }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格（元）" width="120" />
        <el-table-column prop="caution" label="注意事项" width="300">
          <template #default="{ row }">
            <span style="white-space: pre-wrap;">{{ row.caution }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="180">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="openEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleDelete(row.medicine_id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑/添加对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="药品管理"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-loading v-show="loading" element-loading-text="加载中..." />
      
      <el-form 
        :model="form" 
        label-width="120px" 
        ref="formRef"
        :rules="formRules"
      >
        <template v-if="isEditMode">
          <el-form-item label="药品ID" prop="medicine_id">
            <el-input
              v-model.number="form.medicine_id"
              disabled
              placeholder="不可编辑"
            />
          </el-form-item>
        </template>

        <el-form-item label="药品名称" prop="medicine_name">
          <el-input
            v-model.trim="form.medicine_name"
            placeholder="请输入药品名称"
            :rules="formRules.medicine_name"
          />
        </el-form-item>
        
        <el-form-item label="类型" prop="type">
          <el-select
            v-model.number="form.type"
            placeholder="请选择药品类型"
            :rules="formRules.type"
          >
            <el-option label="西药" value="0" />
            <el-option label="中成药" value="1" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="规格" prop="specifications">
          <el-input
            v-model.trim="form.specifications"
            placeholder="请输入规格"
            :rules="formRules.specifications"
          />
        </el-form-item>
        
        <el-form-item label="库存" prop="stock">
          <el-input
            v-model.number="form.stock"
            placeholder="请输入库存数量"
            type="number"
            style="width: 120px;"
            :rules="formRules.stock"
          />
          <el-input
            v-model.trim="form.unit"
            placeholder="请输入单位"
            style="width: 80px; margin-left: 10px;"
            :rules="formRules.unit"
          />
        </el-form-item>
        
        <el-form-item label="价格（元）" prop="price">
          <el-input
            v-model.number="form.price"
            placeholder="请输入价格"
            type="number"
            style="width: 120px;"
            :rules="formRules.price"
          />
        </el-form-item>
        
        <el-form-item label="注意事项" prop="caution">
          <el-input
            v-model.trim="form.caution"
            placeholder="请输入注意事项"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog()">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit()"
          >
            {{ isEditMode ? '保存修改' : '新增药品' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { FormInstance } from 'element-plus';
import axios from "axios";
import { ref, reactive, onMounted } from "vue";

// 状态管理
const medicalRecords = ref<any[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const isEditMode = ref(false);
const form = reactive<{
  medicine_id?: number;
  medicine_name: string;
  type: number;
  specifications: string;
  stock: number;
  unit: string;
  price: number;
  caution: string;
}> ({
  medicine_name: "",
  type: 0,
  specifications: "",
  stock: 0,
  unit: "",
  price: 0,
  caution: ""
});
const formRef = ref<FormInstance>();

// 表单验证规则
const formRules = reactive({
  medicine_name: [{ required: true, message: "请输入药品名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择药品类型", trigger: "change" }],
  specifications: [{ required: true, message: "请输入规格", trigger: "blur" }],
  stock: [
    { required: true, message: "请输入库存数量", trigger: "blur" },
    { type: "number", message: "请输入有效数字", trigger: "blur" }
  ],
  unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
  price: [
    { required: true, message: "请输入价格", trigger: "blur" },
    { type: "number", message: "请输入有效数字", trigger: "blur" }
  ]
});

// 加载数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await axios.get("/medicine/findAll");
    medicalRecords.value = response.data || [];
  } catch (err) {
    console.error("数据加载失败:", err);
    alert('数据加载失败，请检查网络或联系管理员');
  } finally {
    loading.value = false;
  }
};

// 打开添加对话框
const openAddDialog = () => {
  resetForm();
  isEditMode.value = false;
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row: any) => {
  resetForm(row);
  isEditMode.value = true;
  dialogVisible.value = true;
};

// 重置表单
const resetForm = (data?: any) => {
  form.medicine_id = data?.medicine_id || 0;
  form.medicine_name = data?.medicine_name || "";
  form.type = data?.type || 0;
  form.specifications = data?.specifications || "";
  form.stock = data?.stock || 0;
  form.unit = data?.unit || "";
  form.price = data?.price || 0;
  form.caution = data?.caution || "";
};

// 提交表单（添加/更新）
const handleSubmit = async () => {
  if (!formRef.value) return;
  const isValid = await formRef.value.validate();
  if (!isValid) return;

  loading.value = true;
  try {
    const requestData = { 
      ...form, 
      type: Number(form.type), 
      stock: Number(form.stock), 
      price: Number(form.price) 
    };
    
    if (isEditMode.value) {
      await axios.post("/medicine/update", {
        ...requestData,
        medicineId: form.medicine_id
      });
    } else {
      await axios.post("/medicine/add", requestData);
    }
    alert("操作成功");
    dialogVisible.value = false;
    fetchData();
  } catch (err: any) {
    alert(`操作失败：${err.response?.data?.message || "请检查输入或联系管理员"}`);
  } finally {
    loading.value = false;
  }
};

// 删除操作
const handleDelete = async (medicineId: number) => {
  if (!window.confirm("确定要删除该药品吗？此操作不可恢复！")) return;
  
  try {
    await axios.post(
      "/medicine/delete",
      { medicineId: medicineId },
      { headers: { "Content-Type": "application/json" } }
    );
    alert("删除成功");
    fetchData();
  } catch (err: any) {
    alert(`删除失败：${err.response?.data?.message || "网络错误，请重试"}`);
  }
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
};

onMounted(fetchData);
</script>

<style scoped>
/* 整体布局样式 */
.medicine-management {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
}

.button-container {
  width: 100%;
  max-width: 1200px;
  text-align: left;
}

.table-container {
  width: 100%;
  max-width: 1200px;
  margin-top: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 对话框样式优化 */
.el-dialog {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.el-form {
  padding: 24px;
}

.dialog-footer {
  padding: 16px 24px;
  border-top: 1px solid #ebedf0;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 新增：图片样式 */
.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
}

.medicine-image {
  max-width: 80px;
  max-height: 80px;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>